<?php
/*
 * mod/pages/mod.pages.php
 * 
 * Simple pages realization
 * 
 * Copyright (C) 2010, Taras Kudla
 * 
 */
class gModuleContent extends gModule {
	private $table = "mod_pages";
	private $SpaceReplacement = "-";
	private $UseLanguageAlias = false;
	private $DefaultLevel = _FUNC_USER;
	private $AllowedTags = "<b><strong><i><ul><li><ol><img><a><br>";

        /**
         * Module initialization
         */
	public function init(){
		
	}

	# class magic call method, for pages, that are not functions
	public function __call($pageName, $arg){
		if (@preg_match("/([A-z0-9".$this->SpaceReplacement."]{1,250})/", $pageName, $trash)){
			return $this->GetPage($trash[1]);
		}
	}
	# getting page
	private function getpage($page){
		$page  = $this->api->escapeString($page);
		$Query = $this->api->dbo->select($this->table,"id,name,title,content,view,lang","where name='".$page."' limit 1 offset 0",_RESULT_ROW);
		if( count($Query)==6){
			if( strcmp($Query["lang"],$this->api->language())!=0){
			$Query=$this->api->dbo->select($this->table,"id,name,title,content,view,lang","where parent='".$Query["id"]."' and lang='".$this->api->language()."' limit 1 offset 0",_RESULT_ROW);
			if(count($Query)==0)
				return null;
			}
			$this->api->dbo->update($this->table,"set rating=rating+1 where id='".$Query["id"]."' ");    		
			if($this->api->view->detecttemplate("pages","pages/".$page)){
				return $this->api->view->template("pages/".$page,array("id"=>$Query["id"],"name"=>&$Query["title"],"data"=>&$Query["content"]) );
			} else {
				return (bool)$Query["view"]?$this->api->view->template("pages/default",array("id"=>$Query["id"],"name"=>&$Query["title"],"data"=>&$Query["content"])):$this->api->view->template("pages/defaultwithouttitle",array("name"=>&$Query["title"],"data"=>&$Query["content"]));
			}
		}
		return null;	    	
	}
	# pages list vs administration
	public function pageslist(){
		$sort= "created";
		# checking for sorting
		if(isset($_GET["sort"])){
			switch($_GET["sort"]){
				case "title":$sort="title";break;
				case "name":$sort="name";break;
				case "created":$sort="created";break;
				case "lang":$sort="lang";break;
				case "instance":$sort="instance";break;
				case "rating":$sort="rating";break;
				case "author":$sort="author";break;
			}
		}
		$query=$this->api->dbo->select($this->table,"id,title,name,rating,created,instance,lang,author,comment"," order by $sort desc");
		if(count($query)==0)
			return $this->api->message($this->lang->get("p2"));
		return $this->api->view->template("pageslist.php",array("data"=>&$query ),null,true ) ;	 	
	}
	# view page
	public function viewpage(){
		# adding global way
		$this->api->cms->addWay("pagelist",null,$this->lang->get("p19") );
		if(!isset($_GET["page"]) || !is_numeric($_GET["page"])){
			return $this->api->message($this->lang->get("p12"));    	
		}
		$page = $this->api->escapeString($_GET["page"]);
		$Query = $this->api->dbo->select($this->table,"id,title,name,lang,instance,created,view,rating,content,comment,author"," where id='".$page."' limit 1 offset 0",_RESULT_ROW);
		if(count($Query)==0)
			return $this->api->message($this->lang->get("p12"));
		# adding global way
		$this->api->cms->addway("viewpage","page=".$page,$this->lang->get("p11") );
		$function=$this->api->dbo->select("functions","hash"," where  funcname='".$Query["name"]."' and modname='pages' limit 1 offset 0",_RESULT_SINGLE);
		return $this->api->view->template("viewpage",array("data"=>&$Query,"funcid"=>$function ) );     	
	}
	# not allowed page names
	private function notallowed(){
		$result=array();
		$class=get_class_methods($this);
		$added = $this->api->dbo->select($this->table,"name",null,_RESULT_LIST);
		$methods = $this->api->dbo->select("functions","funcname","where modname='pages'",_RESULT_LIST);
		$result=array_merge($class,$added,$methods);
		return $result;
	}
	# alias calculation
	private function buildalias($string,$lang){
		if( $lang=="ru")
		$latin = $this->api->tools->rustotranslit($string);
		else
		$latin = $this->api->tools->ukrtotranslit($string);
		$result = $this->api->tools->preparealiasname($latin);
		return $result;
	}
	# printing a page
	public function printpage(){
		if(!isset($_GET["id"]) || !is_numeric($_GET["id"])){
			return null;
		}
		$id=$this->api->escapeString($_GET["id"]);
		$page=$this->api->dbo->select($this->table,"id,title,content","where id='".$id."' limit 1 offset 0",_RESULT_ROW);
		if(count($page)==0) return null;
		if ($this->api->cms->getobstate() == YES){
			ob_end_clean();
		}
		print $this->api->view->template("pages/print",array("title"=>&$page["title"],"data"=>&$page["content"]));
		$this->api->signal(_SIG_TERM);
		//exit;
	}
	
	# creating new page
	public function newpage(){
		if($this->api->checkPOST("name","lang","instance","data","Submit","comment") ){
			$title=trim($this->api->escapeString($_POST["name"])); 
			$data=preg_replace("/'/","&#039;",$_POST["data"]);
			if(isset($_POST["intelect"])){
				$data=strip_tags($data,$this->AllowedTags);
			}
			list($lang,$instance,$comment) = $this->api->escapePOST("lang","instance","comment");
			$name = $this->buildalias($_POST["name"],$lang);
			# checking if title is not module method
			if (in_array($name,$this->notallowed())){
				print $this->api->message($this->lang->get("p23"));
			# checking if language is correct
			} else if(!in_array($lang,$this->api->syslanguages())){
				print $this->api->message($this->lang->get("p22"));
			# checking if data entered
			} else if( strlen($title)<1 || strlen($name)<1){
				print $this->api->message($this->lang->get("p27"));
			# instance checking  	    	
			} else if(strcmp($instance,"0")!=0 && !preg_match("/[A-z0-9-_]+/",$instance,$tmp)){
				print $this->api->message($this->lang->get("p22"));
			} else {
				if(
					# inserting data into pages table
					$this->api->dbo->insert($this->table, array("name"=>$name,"title"=>$title,"lang"=>$lang,"instance"=>$instance,"content"=>$data,
					"created"=>date("Y-m-d H:i:s"),"comment"=>$comment,"author"=>$this->api->user->GetUserName(),"view"=>(isset($_POST["vh"])?1:0),"rating"=>0))){
					# creating an action
					$this->api->tools->createaction("pages",$name,true);								
			}
				$link = $this->api->cms->htmlactionlink("pageslist",null,$this->lang->get("p28"));
				print $this->api->message($this->lang->get("p29")." ".$link);
			}
		}
		$Query = $this->api->dbo->select("functions","alias"," where modname='pages' and funcname not in ('".implode("','",get_class_methods($this))."') order by alias desc");
		# setting tinymce editor
		$tinymce = $this->api->libload("tinymce");
		$tinymce->set(_TINYMCE_FULL);	
		return $this->api->view->template("newpage",array("language"=>$this->api->language(),"lang"=>$this->api->syslanguages(),"instance"=>$Query));	
	}
	
	# editing a page
	public function editpage(){
		$this->api->cms->addway("pagelist",null,$this->lang->get("p19"));
		if(!isset($_GET["page"]) || !is_numeric($_GET["page"])){
			return $this->api->message($this->lang->get("p12"));
		}
		$page=$this->api->escapeString($_GET["page"]);   	
		$this->api->cms->addway("editpage","page=".$page,$this->lang->get("p18"));
		if(!$this->api->dbo->select($this->table,"lang","where id='".$page."'",_RESULT_BOOL)){
			return $this->api->message($this->lang->get("p12"));
		}
		# getting old infromation about table
		$oldname = $this->api->dbo->select($this->table,"name","where id='$page' limit 1 offset 0",_RESULT_ONE);
		$oldhash = $this->api->cms->gethash("pages",$oldname);
		
		if($this->api->checkPOST("name","lang","instance","data","Submit","comment") ){
			$title=$this->api->escapeString($_POST["name"]);
			$data=preg_replace("/'/","&#039;",$_POST["data"]);
			if(isset($_POST["intelect"])){
				$data=strip_tags($data,$this->AllowedTags);       
			}
			list($lang,$instance,$comment) = $this->api->escapePOST("lang","instance","comment");
			$name = $this->buildalias($_POST["name"],$lang);
			$hash = $this->api->cms->GetHash("pages",$name);
			# Checking all input data
			if (in_array($name,get_class_methods($this))){
				print $this->api->message($this->lang->get("p23"));
			} else if(!in_array($lang,$this->api->syslanguages())){
				print $this->api->message($this->lang->get("p22"));
			} else if($this->api->dbo->select($this->table,"name","where name='$name' and id!='$page'",_RESULT_BOOL)){
				print $this->api->message($this->lang->get("p22")); 	    	
			} else if(strcmp($instance,"0")!=0 && !preg_match("/[A-z0-9-_]+/",$instance,$tmp)){
				print $this->api->message($this->lang->get("p22"));
			} else {
				# updating data in module table
				$this->api->dbo->update($this->table,
				"set name='$name',title='$title',lang='$lang',instance='$instance',comment='$comment',
				content='$data',view='".(isset($_POST["vh"])?1:0)."' where id='$page' " );
				if( $hash!=$oldhash){
					$this->api->dbo->update("functions","set hash='".$hash."',funcname='$name',alias='".$this->api->base->getalias("pages",$name)."' where hash='".$oldhash."' ");
					# updating levellinks
					$this->api->dbo->update("levellinks","set hash='".$hash."' where hash='".$oldhash."' ");
					# updating triggers for menu
					$this->api->dbo->update("langterms","set term='$hash',alias='".$this->api->base->getalias("pages",$name)."' where term='$oldhash'");
				}
				# clearing all menu garbage
				//$this->api->dbo->delete("langterms","where term not in (select hash from functions )");
				$link = $this->api->cms->htmlactionlink("pageslist",null,$this->lang->get("p28"));
				print $this->api->message($this->lang->get("p30")." ".$link);			
			}
		}
		$Query = $this->api->dbo->select("functions","alias"," where modname='pages' order by alias desc");
		$Data  = $this->api->dbo->select($this->table,"name,title,content,lang,instance,view,comment","where id='$page' limit 1 offset 0",_RESULT_ROW);
		if($this->UseLanguageAlias){
			$Data["name"]=preg_replace("/^([A-z]{2,3}-)(.*)$/i","$2",$Data["name"]);    	
		}
		# setting tinymce editor
		$tinymce = $this->api->libload("tinymce");
		$tinymce->set(_TINYMCE_FULL);	
		return $this->api->view->template("editpage",array("language"=>$this->api->language(),"lang"=>$this->api->syslanguages(),"instance"=>&$Query,"data"=>&$Data));    	   	
	}
	# deleting page and all information
	public function deletepage(){
		if(isset($_GET["page"]) && is_numeric($_GET["page"])){
			$page=$this->api->escapeString($_GET["page"]);
			$Data=$this->api->dbo->select($this->table,"name,id","where id='".$page."' limit 1 offset 0",_RESULT_ROW);
			if(count($Data)>0){
				$this->api->dbo->delete("functions","where alias='pages-".$Data["name"]."'");
				$this->api->dbo->delete($this->table,"where id='$page'");
				$this->api->dbo->delete("levellinks","where hash not in (select hash from functions) ");			
			}
		}
		$this->api->cms->redirect("pageslist");
	}

	public function install(){
		# installation
		$table = new sqltable($this->table);
		$table->addfield("id",_FIELD_INTAUTO);
		$table->addfield("name",_FIELD_CHAR);
		$table->addfield("title",_FIELD_CHAR);
		$table->addfield("rating",_FIELD_INT);
		$table->addfield("view",_FIELD_INT);
		$table->addfield("content",_FIELD_TEXT);
		$table->addfield("created",_FIELD_DATETIME);
		$table->addfield("instance",_FIELD_INT);
		$table->addfield("author",_FIELD_CHAR);
		$table->addfield("comment",_FIELD_CHAR);
		$table->addfield("lang",_FIELD_CHAR);
		$table->addkey(_KEY_INDEX,"name");	
		$this->api->dbo->createtable($table);    	
	}	
	public function uninstall(){
		# uninstall
		$this->api->dbo->droptable($this->table);
	}
}